import { useUserStore } from "@/store";

function hasAuth(value, type ="button") {
  const { roles, perms } = useUserStore().user;
  //「超级管理员」拥有所有的按钮权限
  if (type === "button" && roles.includes("ROOT")) {
    return true;
  }
  const auths = type === "button" ? perms : roles;
  return typeof value === "string"
    ? auths.includes(value)
    : auths.some((perm) => {
        return value.includes(perm);
      });
}
/**
 * 按钮权限
 */
export const hasPerm = {
  mounted(el, binding) {
    // DOM绑定需要的按钮权限标识
    const { value } = binding;
    if (value) {
      if (!hasAuth(value)) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error(
        "need perms! Like v-has-perm=\"['sys:user:add','sys:user:edit']\""
      );
    }
  },
};

/**
 * 角色权限
 */
export const hasRole = {
  mounted(el, binding) {
    // DOM绑定需要的角色编码
    const { value } = binding;
    if (value) {
      if (!hasAuth(value, "role")) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("need roles! Like v-has-role=\"['admin','test']\"");
    }
  },
};
